package com.hjm.app.fragment.home;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.hjm.app.activity.GoodsDetailActivity;
import com.hjm.app.activity.StoreActivity;
import com.hjm.java.utils.HjmSuccessCallBack;
import com.hjm.java.utils.HjmFailCallBack;
import com.hjm.java.utils.HjmListCallBack;
import com.hjm.ui.shopcart.entity.ShopCartVO;
import com.hjm.app.R;
import com.hjm.ui.shopcart.ShopCartBottomControl;
import com.hjm.ui.shopcart.ShopCartItem;

import java.util.ArrayList;
import java.util.List;

public class FragmentHomeShopCart extends Fragment implements
        ShopCartBottomControl.Listener,
        ShopCartItem.Listener{
    private static String TAG = "FragmentShopCart";

    private ShopCartItem shopCartItem;
    private ShopCartBottomControl shopCartBottomControl;
    private List<ShopCartVO> shopCartVOList;
    private Handler mHandler;
    private FragmentHomeShopCartListener listener;

    public FragmentHomeShopCart(FragmentHomeShopCartListener listener)  {
        mHandler = new Handler(Looper.getMainLooper());
        this.listener = listener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: 购物车");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: 即将显示");
        listener.getShopCartData((isSuccess, t, message) -> {
            if (isSuccess){
                this.shopCartVOList = t;
                setDataOnView();
            } else {
                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_shop_cart, container, false);
        shopCartItem = view.findViewById(R.id.shop_cart_item);
        shopCartBottomControl = view.findViewById(R.id.shop_cart_bottom_control);

        setDataOnView();
        return view;
    }

    void deleteItem(int orderId){
        for (int i = 0; i< shopCartVOList.size(); i++){
            if (shopCartVOList.get(i).getOrderId() == orderId){
                int temp = i;
                listener.deleteShopCartItem(orderId,
                        ()->{
                            shopCartVOList.remove(temp);
                            shopCartItem.setData(shopCartVOList);
                            shopCartBottomControl.setTotalMoney(String.valueOf(calculateTotalPrice(shopCartVOList)));
                        },
                        msg -> {
                            Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                        });
                break;
            }
        }
    }

    @Override
    public void onSelectAllChanged(boolean isSelectAll) {
        Log.d(TAG, "onSelectAllChanged: 全选 "+isSelectAll);
        for (ShopCartVO goods : shopCartVOList){
            goods.setGoodsSelect(isSelectAll);
        }
        shopCartItem.setData(shopCartVOList);
        shopCartBottomControl.setTotalMoney(String.valueOf(calculateTotalPrice(shopCartVOList)));
    }

    @Override
    public void onDoneClick() {
        Log.d(TAG, "onDoneClick: 结算");

        List<Integer> checkedOrderIds = new ArrayList<>();
        List<ShopCartVO> tempList = new ArrayList<>();
        tempList.addAll(shopCartVOList);
        for (ShopCartVO goods : tempList){
            if (goods.isGoodsSelect()) {
                checkedOrderIds.add(goods.getOrderId());
                shopCartVOList.remove(goods);
            }
        }
        if (checkedOrderIds.size() == 0)
            return;
        int[] orderIds = new int[checkedOrderIds.size()];
        int temp = 0;
        for (int orderId : checkedOrderIds){
            orderIds[temp++] = orderId;
        }

        listener.shopCartPay(orderIds);
        shopCartItem.setData(shopCartVOList);
        shopCartBottomControl.setTotalMoney(String.valueOf(calculateTotalPrice(shopCartVOList)));
    }

    @Override
    public void onNumChanged(int num,int orderId) {
        Log.d(TAG, "onNumChanged: 数量变化 id:"+ orderId +" num:"+num);
        if (num==0){
            Log.d(TAG, "numChanged: 需要删除 "+orderId);
            deleteItem(orderId);
        }
        listener.updateShopCartItem(orderId, num,
                ()->{
                    shopCartItem.setData(shopCartVOList);
                    shopCartBottomControl.setTotalMoney(String.valueOf(calculateTotalPrice(shopCartVOList)));
                },
                msg -> {
                    Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                });
    }

    @Override
    public void selectChanged(boolean isSelect, int goodsId) {
        Log.d(TAG, "onSelect: 选中变化 id:"+ goodsId +" isSelect:"+isSelect);
        shopCartItem.setData(shopCartVOList);
        shopCartBottomControl.setTotalMoney(String.valueOf(calculateTotalPrice(shopCartVOList)));
    }

    @Override
    public void selectStoreAllChanged(boolean isSelectAll, int storeId) {
        shopCartItem.setData(shopCartVOList);
        shopCartBottomControl.setTotalMoney(String.valueOf(calculateTotalPrice(shopCartVOList)));
    }

    @Override
    public void onItemClick(int goodsId) {
        Log.d(TAG, "itemClick: 商品点击 id:"+goodsId);
        Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
        intent.putExtra("goodsId", goodsId);
        startActivity(intent);
    }

    @Override
    public void onStoreNameClick(int storeId) {
        Log.d(TAG, "onStoreNameClick: 店铺名称点击 storeId:"+storeId);
        Intent intent = new Intent(getActivity(), StoreActivity.class);
        intent.putExtra("storeId", storeId);
        startActivity(intent);
    }

    public void setDataOnView(){
        if (shopCartVOList == null)
            shopCartVOList = new ArrayList<>();

        shopCartItem.setData(shopCartVOList);
        shopCartItem.setListener(this);

        shopCartBottomControl.setListener(this);
    }

    int calculateTotalPrice(List<ShopCartVO> goodsList){
        int totalPrice = 0;
        for (ShopCartVO goods : goodsList){
            if (goods.isGoodsSelect()){
                totalPrice += goods.getGoodsNum() * goods.getPrice().floatValue();
            }
        }
        return totalPrice;
    }

    public interface FragmentHomeShopCartListener{
        void updateShopCartItem(int orderId, int num, HjmSuccessCallBack callBack, HjmFailCallBack failCallBack);
        void deleteShopCartItem(int orderId, HjmSuccessCallBack callBack, HjmFailCallBack failCallBack);
        void getShopCartData(HjmListCallBack<ShopCartVO> listCallBack);
        void shopCartPay(int[] orderIds);
    }
}